package com.shop.controller;

import com.shop.common.Constants;

import com.shop.dto.CarItem;
import com.shop.model.Cart;
import com.shop.model.User;
import com.shop.service.CartService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Lenovo
 * @version 1.0
 * @date 2025/4/29 11:19
 * @className CartController
 */
@Controller
@RequestMapping("/cart")
public class CartController {
    @Autowired
    private CartService cartService;

    //展示购物车
    @GetMapping("/show")
    public String showCart(Model model, HttpSession session) {
        User user = (User) session.getAttribute(Constants.Session.USER);
        if (user != null) {
            Long userId = user.getId();
            List<CarItem> cartItems = cartService.getCartItemsByUserId(userId);
//            int a=cartService.addCartItem(cartItems);
//            if (a==0){
//                return "redirect:/cart/show";
//            }
            int cartItemCount = cartItems != null ? cartItems.size() : 0;
            model.addAttribute("cartItemCount", cartItemCount);
            model.addAttribute("cartList", cartItems); // 使用CarItem列表
        }
        return "cart/show";
    }
    //删除购物车商品
    @PostMapping("/decreaseQuantity")
    @ResponseBody
    public Map<String, Object> decreaseQuantity(@RequestParam("goodId") Long goodId) {
        return cartService.decreaseQuantity(goodId);
    }

    //购物车商品加一操作

    @PostMapping("/increaseQuantity")
    @ResponseBody
    public Map<String, Object> increaseQuantity(@RequestParam("goodId") Long goodId) {
        return cartService.increaseQuantity(goodId);
    }

    //购物车商品减一操作
    @PostMapping("/deleteCartItem")
    @ResponseBody
    public Map<String, Object> deleteCartItem(@RequestParam("goodId") Long goodId) {
        return cartService.deleteCartItem(goodId);
    }


    //结算
    @PostMapping("/checkout")
    @ResponseBody
    public Map<String, Object> checkout(
            @RequestParam("goodId") Long goodId,
            @RequestParam("cartId") Long cartId,
            @RequestParam("count") int count) {
        return cartService.checkout(goodId, cartId, count);
    }


    // 加入购物车
    @GetMapping("/add")
    @ResponseBody
    public Map<String, Object> add(@RequestParam("id") Long goodId,
                                   @RequestParam("num") int count,
                                   @RequestParam("price") double totalPrice,
                                   HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        User user = (User) session.getAttribute(Constants.Session.USER);
        if (user != null) {
            try {
                Long userId = user.getId();
                // 检查购物车中是否已有该商品
                Cart existingCart = cartService.getCartByUserIdAndGoodId(userId, goodId);
                if (existingCart != null) {
                    // 如果已有，更新数量和价格
                    existingCart.setCount(existingCart.getCount() + count);
                    existingCart.setPrice(existingCart.getPrice() + totalPrice);
                    cartService.updateCart(existingCart);
                } else {
                    // 如果没有，创建新记录
                    Cart cart = new Cart();
                    cart.setUserId(Math.toIntExact(userId));
                    cart.setGoodId(Math.toIntExact(goodId));
                    cart.setCount(count);
                    cart.setPrice(totalPrice);
                    cartService.addCart(cart);
                }
                result.put("success", true);
                result.put("message", "商品已成功加入购物车");

                // 获取购物车数量并返回
                List<Cart> cartList = cartService.getCartsByUserId(userId);
                int countInCart = cartList != null ? cartList.size() : 0;
                result.put("count", countInCart);
            } catch (Exception e) {
                result.put("success", false);
                result.put("message", "加入购物车失败：" + e.getMessage());
                e.printStackTrace();
            }
        } else {
            result.put("success", false);
            result.put("message", "请先登录");
        }
        return result;
    }

    // 获得购物车数量
    @GetMapping("/getCount")
    @ResponseBody
    public Map<String, Object> getCartCount(HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        User user = (User) session.getAttribute(Constants.Session.USER);
        if (user != null) {
            Long userId = user.getId();
            List<Cart> cartList = cartService.getCartsByUserId(userId);
            int count = cartList != null ? cartList.size() : 0;
            result.put("success", true);
            result.put("count", count);
        } else {
            result.put("success", false);
            result.put("count", 0);
        }
        return result;
    }

}